// pages/profile/index.ts
const app = getApp()
Page({
  data: {
    avatar: '',
    nickName: ''
  },
  onShow () {
    this.getUserInfo()
  },
  getUserInfo () {
    this.setData({ avatar: app.avatar, nickName: app.nickName })
  },
  async setUserName (ev) {
    if (ev.detail.value === '') return
    const { code, message } = await wx.http.put('/userInfo', { nickName: ev.detail.value })
    if (code !== 10000) return wx.utils.toast(message)
    this.setData({ nickName: ev.detail.value })
    console.log(message)
    app.setUserinfo('nickName', ev.detail.value)
  },
  getUserAvatar(ev) {
    console.log(ev);
    wx.uploadFile({
      filePath: ev.detail.avatarUrl,
      name: 'file',
      url: wx.http.baseURL + '/upload',
      header: {
        Authorization: `Bearer ${app.token}`
      },
      formData: { type: 'avatar' },
      success: ({ data }) => {
        const res = JSON.parse(data)
        if (res.code !== 10000) return wx.utils.toast('上传头像失败!')
        this.setData({ avatar: res.data.url })
        app.setUserinfo('avatar', res.data.url)
      }
    })
  }
})
